package com.gate.ws.spring.process.upmsg;

import com.gate.ws.spring.constants.ChannelConstants;
import com.nami.basic.enums.protocol.DownCMDEnum;
import com.nami.basic.packet.Packet;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PingProcess implements PacketProcessor {

    private static final Logger log = LoggerFactory.getLogger(PingProcess.class);


    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        try {
            String userId = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get();
            // 刷新ping 时间
            channel.attr(AttributeKey.valueOf(ChannelConstants.READ_TIME)).set(System.currentTimeMillis());
            channel.writeAndFlush(newPacket());
            log.info("[pong] 用户：【{}】。通道【{}】交互正常", userId, channel.remoteAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static @NotNull Packet newPacket() {
        // 12 字节 pong 包
        Packet resp = new Packet();
        resp.setMagic((byte) 8);
        resp.setCmd(DownCMDEnum.PONG.getCode());
        resp.setVersion((byte) 0);
        resp.setSerial((byte) 0);
        resp.setEncrypt((byte) 0);
//        resp.setBody("".getBytes(StandardCharsets.UTF_8));
        resp.setBody(new byte[0]);
        return resp;
    }

}
